package net.sf.rose.mail;

import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * @author fengjian
 * 
 */
public class SMTPMail {

	/**
	 * 此方法邮件内容只在中文环境中没有问题，其它语言可能存在字符编码问题
	 */
	public void sendMail(SMTPMailBean mb) {
		String[] to = mb.getTo();
		String subject = mb.getSubject();
		String content = mb.getContent();
		String fileName = mb.getFilename();
		Vector<String> file = mb.getFile();

		if (host == null || to == null || to.length == 0) {
			return;
		}

		try {
			// 设置SMTP的服务器的IP地址
			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);

			// 根据有无用户名决定是否需要验证，并创建Sessiont和Message对象
			Session session = null;
			if (username == null) {
				props.put("mail.smtp.auth", "false"); // 不需要经过验证
				session = Session.getInstance(props);
			} else {
				props.put("mail.smtp.auth", "true"); // 需要经过验证
				session = Session.getInstance(props, new Authenticator() {
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});
			}
			// session.setDebug(true);
			MimeMessage msg = new MimeMessage(session);

			// 设置收件人地址
			InternetAddress[] address = new InternetAddress[to.length];
			for (int i = 0; i < address.length; i++) {
				address[i] = new InternetAddress(to[i]);
			}
			msg.setRecipients(Message.RecipientType.TO, address);

			// 设置发件人和标题
			msg.setFrom(new InternetAddress(from));
			msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
			//msg.setSubject(toChinese(subject));

			// 设置邮件正文
			Multipart mp = new MimeMultipart();
			MimeBodyPart mbpContent = new MimeBodyPart();
			mbpContent.setText(content);
			mp.addBodyPart(mbpContent);

			// 添加邮件附件
			if (file != null) {
				Enumeration<String> efile = file.elements();
				while (efile.hasMoreElements()) {
					MimeBodyPart mbpFile = new MimeBodyPart();
					fileName = efile.nextElement().toString();
					FileDataSource fds = new FileDataSource(fileName);
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(toChinese(fds.getName()));
					mp.addBodyPart(mbpFile);
				}
			}

			// 发送邮件
			msg.setContent(mp);
			msg.setSentDate(new Date());
			Transport.send(msg);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 
	 */
	private String toChinese(String text) {
		try {
			text = MimeUtility.encodeText(new String(text.getBytes(), "GB2312"), "GB2312", "B");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return text;
	}

	/**
	 * 主机名
	 */
	private String host = null;

	/**
	 * 用户名
	 */
	private String username = null;

	/**
	 * 密码
	 */
	private String password = null;

	/**
	 * 发件人
	 */
	private String from = null;

	/**
	 * @return 主机名
	 */
	public String getHost() {
		return host;
	}

	/**
	 * @param 主机名
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 * @return 用户名
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param 用户名
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return 密码
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param 密码
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return 发件人
	 */
	public String getFrom() {
		return from;
	}

	/**
	 * @param 发件人
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	public static void testSina(){
		SMTPMailBean bean = new SMTPMailBean();
		bean.setTo(new String[]{"9110530@qq.com"});
		bean.setSubject("hello");
		bean.setContent("你好");
		SMTPMail mail = new SMTPMail();
		mail.setHost("smtp.sina.com");
		mail.setUsername("fgg047");
		mail.setPassword("811260");
		mail.setFrom("fgg047@sina.com ");
		mail.sendMail(bean);
	}
	
	public static void test163(){
		SMTPMailBean bean = new SMTPMailBean();
		bean.setTo(new String[]{"9110530@qq.com"});
		bean.setSubject("hello");
		bean.setContent("你好");
		SMTPMail mail = new SMTPMail();
		mail.setHost("smtp.ym.163.com");
		mail.setUsername("fengj@jsruyun.com");
		mail.setPassword("784533");
		mail.setFrom("fengj@jsruyun.com ");
		mail.sendMail(bean);
	}
	
	public static void testqq(){
		SMTPMailBean bean = new SMTPMailBean();
		bean.setTo(new String[]{"9110530@qq.com"});
		bean.setSubject("hello");
		bean.setContent("你好");
		SMTPMail mail = new SMTPMail();
		mail.setHost("smtp.qq.com");
		mail.setUsername("784816599");
		mail.setPassword("fengjianwangping");
		mail.setFrom("784816599@qq.com ");
		mail.sendMail(bean);
	}
	
	//mail.qq.com
	public static void main(String argv[]) throws Exception {
		test163();
	}
}
